<template>
  <div class="notification-management">
    <div class="header">
      <h2>通知管理</h2>
      <div class="header-actions">
        <button @click="showAddDialog = true" class="btn btn-primary">
          <i class="fas fa-plus"></i> 新增通知
        </button>
        <button @click="showSystemNotificationDialog = true" class="btn btn-success">
          <i class="fas fa-broadcast-tower"></i> 系统广播
        </button>
      </div>
    </div>

    <!-- 搜索过滤区域 -->
    <div class="filter-section">
      <div class="filter-row">
        <div class="filter-item">
          <label>标题关键词:</label>
          <input
            v-model="searchParams.title"
            type="text"
            placeholder="通知标题"
            class="form-input"
            @keyup.enter="loadNotificationList"
          />
        </div>
        <div class="filter-item">
          <label>通知类型:</label>
          <select v-model.number="searchParams.type" class="form-select">
            <option value="">全部类型</option>
            <option :value="1">系统通知</option>
            <option :value="2">订单通知</option>
            <option :value="3">商品通知</option>
            <option :value="4">安全通知</option>
          </select>
        </div>
        <div class="filter-item">
          <label>通知级别:</label>
          <select v-model.number="searchParams.level" class="form-select">
            <option value="">全部级别</option>
            <option :value="1">普通</option>
            <option :value="2">重要</option>
            <option :value="3">紧急</option>
          </select>
        </div>
        <div class="filter-item">
          <label>阅读状态:</label>
          <select v-model.number="searchParams.isRead" class="form-select">
            <option value="">全部状态</option>
            <option :value="0">未读</option>
            <option :value="1">已读</option>
          </select>
        </div>
        <div class="filter-item">
          <label>用户ID:</label>
          <input
            v-model.number="searchParams.userId"
            type="number"
            placeholder="用户ID"
            class="form-input"
            @keyup.enter="loadNotificationList"
          />
        </div>
        <div class="filter-actions">
          <button @click="loadNotificationList" class="btn btn-info">
            <i class="fas fa-search"></i> 搜索
          </button>
          <button @click="resetSearch" class="btn btn-secondary">
            <i class="fas fa-redo"></i> 重置
          </button>
        </div>
      </div>
    </div>

    <!-- 通知统计卡片 -->
    <div class="stats-section">
      <div class="stat-card">
        <div class="stat-icon total">
          <i class="fas fa-bell"></i>
        </div>
        <div class="stat-info">
          <h3>{{ notificationStats.total }}</h3>
          <p>总通知数</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon unread">
          <i class="fas fa-envelope"></i>
        </div>
        <div class="stat-info">
          <h3>{{ notificationStats.unread }}</h3>
          <p>未读通知</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon urgent">
          <i class="fas fa-exclamation-triangle"></i>
        </div>
        <div class="stat-info">
          <h3>{{ notificationStats.urgent }}</h3>
          <p>紧急通知</p>
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-icon system">
          <i class="fas fa-cog"></i>
        </div>
        <div class="stat-info">
          <h3>{{ notificationStats.system }}</h3>
          <p>系统通知</p>
        </div>
      </div>
    </div>

    <!-- 通知列表表格 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
          <tr>
            <th width="60">
              <input type="checkbox" v-model="selectAll" @change="toggleSelectAll" />
            </th>
            <th width="80">ID</th>
            <th width="100">用户ID</th>
            <th width="200">标题</th>
            <th width="300">内容</th>
            <th width="80">类型</th>
            <th width="80">级别</th>
            <th width="80">状态</th>
            <th width="120">关联信息</th>
            <th width="120">创建时间</th>
            <th width="120">阅读时间</th>
            <th width="150">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="notification in notificationList" :key="notification.id">
            <td>
              <input type="checkbox" v-model="selectedIds" :value="notification.id" />
            </td>
            <td>{{ notification.id }}</td>
            <td>{{ notification.userId || '-' }}</td>
            <td class="notification-title">
              <div class="title-content">
                <strong :class="{ unread: notification.isRead === 0 }">{{ notification.title }}</strong>
                <span v-if="notification.actionUrl" class="has-action">
                  <i class="fas fa-link"></i>
                </span>
              </div>
            </td>
            <td class="notification-content">
              <div class="content-preview" :title="notification.content">
                {{ notification.content }}
              </div>
            </td>
            <td>
              <span :class="['type-badge', `type-${notification.type}`]">
                {{ getTypeText(notification.type) }}
              </span>
            </td>
            <td>
              <span :class="['level-badge', `level-${notification.level}`]">
                {{ getLevelText(notification.level) }}
              </span>
            </td>
            <td>
              <span :class="['read-badge', notification.isRead === 1 ? 'read' : 'unread']">
                <i :class="notification.isRead === 1 ? 'fas fa-envelope-open' : 'fas fa-envelope'"></i>
                {{ notification.isRead === 1 ? '已读' : '未读' }}
              </span>
            </td>
            <td class="related-info">
              <div v-if="notification.relatedType">
                <span class="related-type">{{ notification.relatedType }}</span>
                <span v-if="notification.relatedId" class="related-id">#{{ notification.relatedId }}</span>
              </div>
              <span v-else class="no-relation">-</span>
            </td>
            <td>{{ formatDateTime(notification.createdTime) }}</td>
            <td>
              {{ notification.readTime ? formatDateTime(notification.readTime) : '-' }}
            </td>
            <td class="actions">
              <button @click="viewNotification(notification)" class="btn btn-sm btn-info">
                <i class="fas fa-eye"></i> 查看
              </button>
              <button @click="editNotification(notification)" class="btn btn-sm btn-warning">
                <i class="fas fa-edit"></i> 编辑
              </button>
              <button @click="deleteNotificationAction(notification)" class="btn btn-sm btn-danger">
                <i class="fas fa-trash"></i> 删除
              </button>
            </td>
          </tr>
          <tr v-if="notificationList.length === 0">
            <td colspan="12" class="no-data">暂无通知数据</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 批量操作栏 -->
    <div v-if="selectedIds.length > 0" class="batch-actions">
      <div class="batch-info">
        已选择 {{ selectedIds.length }} 条通知
      </div>
      <div class="batch-buttons">
        <button @click="batchMarkAsRead" class="btn btn-success">
          <i class="fas fa-check"></i> 批量标记已读
        </button>
        <button @click="batchDelete" class="btn btn-danger">
          <i class="fas fa-trash"></i> 批量删除
        </button>
      </div>
    </div>

    <!-- 分页组件 -->
    <div class="pagination-section">
      <div class="pagination-info">
        共 {{ total }} 条记录，第 {{ current }} / {{ Math.ceil(total / pageSize) }} 页
      </div>
      <div class="pagination-controls">
        <button
          @click="changePage(current - 1)"
          :disabled="current <= 1"
          class="btn btn-sm btn-secondary"
        >
          上一页
        </button>
        <span class="page-numbers">
          <button
            v-for="page in getPageNumbers()"
            :key="page"
            @click="changePage(page)"
            :class="['btn', 'btn-sm', page === current ? 'btn-primary' : 'btn-outline']"
          >
            {{ page }}
          </button>
        </span>
        <button
          @click="changePage(current + 1)"
          :disabled="current >= Math.ceil(total / pageSize)"
          class="btn btn-sm btn-secondary"
        >
          下一页
        </button>
      </div>
    </div>

    <!-- 新增/编辑通知弹窗 -->
    <div v-if="showAddDialog || showEditDialog" class="modal-overlay">
      <div class="modal-content notification-form-modal" @click.stop>
        <div class="modal-header">
          <h3>{{ showEditDialog ? '编辑通知' : '新增通知' }}</h3>
          <button @click="closeDialog" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveNotificationData">
            <div class="form-group">
              <label>接收用户 *</label>
              <input v-model.number="formData.userId" type="number" required class="form-input" placeholder="用户ID，留空表示系统通知" />
            </div>
            <div class="form-group">
              <label>通知标题 *</label>
              <input v-model="formData.title" type="text" required class="form-input" placeholder="请输入通知标题" />
            </div>
            <div class="form-group">
              <label>通知内容 *</label>
              <textarea v-model="formData.content" required class="form-textarea" rows="4" placeholder="请输入通知内容"></textarea>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>通知类型</label>
                <select v-model.number="formData.type" class="form-select">
                  <option :value="1">系统通知</option>
                  <option :value="2">订单通知</option>
                  <option :value="3">商品通知</option>
                  <option :value="4">安全通知</option>
                </select>
              </div>
              <div class="form-group">
                <label>通知级别</label>
                <select v-model.number="formData.level" class="form-select">
                  <option :value="1">普通</option>
                  <option :value="2">重要</option>
                  <option :value="3">紧急</option>
                </select>
              </div>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>关联类型</label>
                <input v-model="formData.relatedType" type="text" class="form-input" placeholder="如: order, product, user" />
              </div>
              <div class="form-group">
                <label>关联ID</label>
                <input v-model.number="formData.relatedId" type="number" class="form-input" placeholder="关联对象的ID" />
              </div>
            </div>
            <div class="form-group">
              <label>操作链接</label>
              <input v-model="formData.actionUrl" type="url" class="form-input" placeholder="点击通知后跳转的链接" />
            </div>
            <div class="form-group">
              <label>过期时间</label>
              <input v-model="formData.expireTime" type="datetime-local" class="form-input" />
            </div>
            <div class="form-group">
              <label>额外数据(JSON)</label>
              <textarea v-model="formData.extraData" class="form-textarea" rows="3" placeholder='{"key": "value"}'></textarea>
            </div>
            <div class="form-actions">
              <button type="button" @click="closeDialog" class="btn btn-secondary">取消</button>
              <button type="submit" :disabled="saving" class="btn btn-primary">
                {{ saving ? '保存中...' : '保存' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 系统广播通知弹窗 -->
    <div v-if="showSystemNotificationDialog" class="modal-overlay">
      <div class="modal-content system-notification-modal" @click.stop>
        <div class="modal-header">
          <h3>系统广播通知</h3>
          <button @click="closeSystemDialog" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="sendSystemNotification">
            <div class="form-group">
              <label>通知标题 *</label>
              <input v-model="systemNotificationData.title" type="text" required class="form-input" />
            </div>
            <div class="form-group">
              <label>通知内容 *</label>
              <textarea v-model="systemNotificationData.content" required class="form-textarea" rows="4"></textarea>
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>通知级别</label>
                <select v-model.number="systemNotificationData.level" class="form-select">
                  <option :value="1">普通</option>
                  <option :value="2">重要</option>
                  <option :value="3">紧急</option>
                </select>
              </div>
              <div class="form-group">
                <label>目标用户</label>
                <select v-model.number="systemNotificationData.targetType" class="form-select">
                  <option :value="0">所有用户</option>
                  <option :value="1">所有用户</option>
                  <option :value="2">所有会员</option>
                </select>
              </div>
            </div>
            <div class="form-actions">
              <button type="button" @click="closeSystemDialog" class="btn btn-secondary">取消</button>
              <button type="submit" :disabled="saving" class="btn btn-success">
                {{ saving ? '发送中...' : '发送广播' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 通知详情弹窗 -->
    <div v-if="showDetailDialog" class="modal-overlay">
      <div class="modal-content notification-detail-modal" @click.stop>
        <div class="modal-header">
          <h3>通知详情</h3>
          <button @click="closeDetailDialog" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <div v-if="selectedNotification" class="notification-detail">
            <div class="detail-section">
              <h4>基本信息</h4>
              <div class="detail-row">
                <span class="label">通知ID:</span>
                <span class="value">{{ selectedNotification.id }}</span>
              </div>
              <div class="detail-row">
                <span class="label">标题:</span>
                <span class="value">{{ selectedNotification.title }}</span>
              </div>
              <div class="detail-row">
                <span class="label">内容:</span>
                <span class="value">{{ selectedNotification.content }}</span>
              </div>
              <div class="detail-row">
                <span class="label">类型:</span>
                <span :class="['value', 'type-badge', `type-${selectedNotification.type}`]">
                  {{ getTypeText(selectedNotification.type) }}
                </span>
              </div>
              <div class="detail-row">
                <span class="label">级别:</span>
                <span :class="['value', 'level-badge', `level-${selectedNotification.level}`]">
                  {{ getLevelText(selectedNotification.level) }}
                </span>
              </div>
            </div>

            <div class="detail-section">
              <h4>接收信息</h4>
              <div class="detail-row">
                <span class="label">用户ID:</span>
                <span class="value">{{ selectedNotification.userId || '系统广播' }}</span>
              </div>
              <div class="detail-row">
                <span class="label">阅读状态:</span>
                <span :class="['value', 'read-badge', selectedNotification.isRead === 1 ? 'read' : 'unread']">
                  {{ selectedNotification.isRead === 1 ? '已读' : '未读' }}
                </span>
              </div>
              <div v-if="selectedNotification.readTime" class="detail-row">
                <span class="label">阅读时间:</span>
                <span class="value">{{ formatDateTime(selectedNotification.readTime) }}</span>
              </div>
            </div>

            <div v-if="selectedNotification.relatedType || selectedNotification.actionUrl" class="detail-section">
              <h4>关联信息</h4>
              <div v-if="selectedNotification.relatedType" class="detail-row">
                <span class="label">关联类型:</span>
                <span class="value">{{ selectedNotification.relatedType }}</span>
              </div>
              <div v-if="selectedNotification.relatedId" class="detail-row">
                <span class="label">关联ID:</span>
                <span class="value">{{ selectedNotification.relatedId }}</span>
              </div>
              <div v-if="selectedNotification.actionUrl" class="detail-row">
                <span class="label">操作链接:</span>
                <span class="value">
                  <a :href="selectedNotification.actionUrl" target="_blank">{{ selectedNotification.actionUrl }}</a>
                </span>
              </div>
            </div>

            <div class="detail-section">
              <h4>时间信息</h4>
              <div class="detail-row">
                <span class="label">创建时间:</span>
                <span class="value">{{ formatDateTime(selectedNotification.createdTime) }}</span>
              </div>
              <div class="detail-row">
                <span class="label">更新时间:</span>
                <span class="value">{{ formatDateTime(selectedNotification.updatedTime) }}</span>
              </div>
              <div v-if="selectedNotification.expireTime" class="detail-row">
                <span class="label">过期时间:</span>
                <span class="value">{{ formatDateTime(selectedNotification.expireTime) }}</span>
              </div>
            </div>

            <div v-if="selectedNotification.extraData" class="detail-section">
              <h4>额外数据</h4>
              <pre class="extra-data">{{ selectedNotification.extraData }}</pre>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="closeDetailDialog" class="btn btn-secondary">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { getNotificationList, saveNotification, updateNotification, deleteNotifications, sendSystemAlertNotification } from '@/api/notification'
import type { Notification, SystemAlertDTO } from '@/types/notification'

// 响应式数据
const notificationList = ref<Notification[]>([])
const total = ref(0)
const current = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const saving = ref(false)

// 弹窗状态
const showAddDialog = ref(false)
const showEditDialog = ref(false)
const showSystemNotificationDialog = ref(false)
const showDetailDialog = ref(false)
const currentNotification = ref<Notification | null>(null)
const selectedNotification = ref<Notification | null>(null)

// 选择状态
const selectedIds = ref<number[]>([])
const selectAll = ref(false)

// 通知统计
const notificationStats = reactive({
  total: 0,
  unread: 0,
  urgent: 0,
  system: 0
})

// 搜索参数
const searchParams = reactive({
  title: '',
  type: undefined as number | undefined,
  level: undefined as number | undefined,
  isRead: undefined as number | undefined,
  userId: undefined as number | undefined
})

// 表单数据
const formData = reactive({
  id: 0,
  userId: undefined as number | undefined,
  title: '',
  content: '',
  type: 1,
  level: 1,
  relatedType: '',
  relatedId: undefined as number | undefined,
  actionUrl: '',
  expireTime: '',
  extraData: ''
})

// 系统通知数据
const systemNotificationData = reactive({
  title: '',
  content: '',
  level: 1,
  targetType: 0 // Changed from string to number
})

// 加载通知列表
const loadNotificationList = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: current.value,
      pageSize: pageSize.value,
      ...searchParams
    }
    const response = await getNotificationList(params.pageNo, params.pageSize, params)
    notificationList.value = response.data.records
    total.value = response.data.total
    
    // 更新统计数据
    updateNotificationStats()
  } catch (error) {
    console.error('加载通知列表失败:', error)
    alert('加载通知列表失败')
  } finally {
    loading.value = false
  }
}

// 更新通知统计
const updateNotificationStats = () => {
  const stats = {
    total: notificationList.value.length,
    unread: 0,
    urgent: 0,
    system: 0
  }
  
  notificationList.value.forEach(notification => {
    if (notification.isRead === 0) stats.unread++
    if (notification.level === 3) stats.urgent++
    if (notification.type === 1) stats.system++
  })
  
  Object.assign(notificationStats, stats)
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchParams, {
    title: '',
    type: undefined,
    level: undefined,
    isRead: undefined,
    userId: undefined
  })
  current.value = 1
  loadNotificationList()
}

// 分页切换
const changePage = (page: number) => {
  if (page < 1 || page > Math.ceil(total.value / pageSize.value)) return
  current.value = page
  loadNotificationList()
}

// 获取分页数字
const getPageNumbers = () => {
  const nums: number[] = []
  const totalPages = Math.ceil(total.value / pageSize.value)
  const start = Math.max(1, current.value - 2)
  const end = Math.min(totalPages, current.value + 2)
  
  for (let i = start; i <= end; i++) {
    nums.push(i)
  }
  return nums
}

// 全选切换
const toggleSelectAll = () => {
  if (selectAll.value) {
    selectedIds.value = notificationList.value.map(n => n.id!).filter(Boolean)
  } else {
    selectedIds.value = []
  }
}

// 查看通知详情
const viewNotification = (notification: Notification) => {
  selectedNotification.value = notification
  showDetailDialog.value = true
}

// 编辑通知
const editNotification = (notification: Notification) => {
  currentNotification.value = notification
  Object.assign(formData, {
    id: notification.id,
    userId: notification.userId,
    title: notification.title,
    content: notification.content,
    type: notification.type,
    level: notification.level,
    relatedType: notification.relatedType || '',
    relatedId: notification.relatedId,
    actionUrl: notification.actionUrl || '',
    expireTime: notification.expireTime ? new Date(notification.expireTime).toISOString().slice(0, 16) : '',
    extraData: notification.extraData || ''
  })
  showEditDialog.value = true
}

// 删除通知
const deleteNotificationAction = async (notification: Notification) => {
  if (!confirm(`确定要删除通知"${notification.title}"吗？`)) return
  
  try {
    await deleteNotifications([notification.id!])
    alert('删除成功')
    loadNotificationList()
  } catch (error) {
    console.error('删除通知失败:', error)
    alert('删除通知失败')
  }
}

// 批量标记已读
const batchMarkAsRead = async () => {
  if (!confirm(`确定要将选中的 ${selectedIds.value.length} 条通知标记为已读吗？`)) return
  
  try {
    // 这里需要API支持批量标记已读
    alert('批量标记已读功能需要后端支持')
    selectedIds.value = []
    selectAll.value = false
  } catch (error) {
    console.error('批量标记已读失败:', error)
    alert('批量标记已读失败')
  }
}

// 批量删除
const batchDelete = async () => {
  if (!confirm(`确定要删除选中的 ${selectedIds.value.length} 条通知吗？`)) return
  
  try {
    await deleteNotifications(selectedIds.value)
    alert('批量删除成功')
    selectedIds.value = []
    selectAll.value = false
    loadNotificationList()
  } catch (error) {
    console.error('批量删除失败:', error)
    alert('批量删除失败')
  }
}

// 保存通知
const saveNotificationData = async () => {
  saving.value = true
  try {
    // 验证必填字段
    if (!formData.title.trim()) {
      alert('标题不能为空')
      saving.value = false
      return
    }
    if (!formData.content.trim()) {
      alert('内容不能为空')
      saving.value = false
      return
    }

    // 处理空字符串为undefined，避免发送空字符串到后端
    const notificationData: any = {
      userId: formData.userId || undefined,
      title: formData.title.trim(),
      content: formData.content.trim(),
      type: formData.type,
      level: formData.level,
      isRead: 0,
      relatedType: formData.relatedType?.trim() || undefined,
      relatedId: formData.relatedId || undefined,
      actionUrl: formData.actionUrl?.trim() || undefined,
      expireTime: formData.expireTime ? (() => {
        const expireDate = new Date(formData.expireTime)
        return isNaN(expireDate.getTime()) ? undefined : formatDateTimeForBackend(expireDate)
      })() : undefined,
      extraData: formData.extraData?.trim() || undefined,
      isDel: 0,
      createdTime: formatDateTimeForBackend(new Date()),
      updatedTime: formatDateTimeForBackend(new Date())
    }

    // 移除undefined字段，只发送有值的字段
    Object.keys(notificationData).forEach(key => {
      if (notificationData[key] === undefined) {
        delete notificationData[key]
      }
    })

    if (showEditDialog.value && currentNotification.value) {
      notificationData.id = currentNotification.value.id
      await updateNotification(notificationData)
      alert('更新成功')
    } else {
      console.log('发送到后端的通知数据:', notificationData)
      await saveNotification(notificationData)
      alert('创建成功')
    }
    
    closeDialog()
    loadNotificationList()
  } catch (error: any) {
    console.error('保存通知失败:', error)
    console.error('错误详情:', error?.response?.data)
    const errorMessage = error?.response?.data?.message || error?.message || '未知错误'
    alert(`保存通知失败: ${errorMessage}`)
  } finally {
    saving.value = false
  }
}

// 发送系统通知
const sendSystemNotification = async () => {
  saving.value = true
  try {
    const systemAlertData: SystemAlertDTO = {
      title: systemNotificationData.title,
      content: systemNotificationData.content,
      level: systemNotificationData.level,
      targetType: systemNotificationData.targetType
    }
    
    await sendSystemAlertNotification(systemAlertData)
    alert('系统广播发送成功')
    closeSystemDialog()
    loadNotificationList()
  } catch (error) {
    console.error('发送系统通知失败:', error)
    alert('发送系统通知失败')
  } finally {
    saving.value = false
  }
}

// 关闭弹窗
const closeDialog = () => {
  showAddDialog.value = false
  showEditDialog.value = false
  currentNotification.value = null
  Object.assign(formData, {
    id: 0,
    userId: undefined,
    title: '',
    content: '',
    type: 1,
    level: 1,
    relatedType: '',
    relatedId: undefined,
    actionUrl: '',
    expireTime: '',
    extraData: ''
  })
}

const closeSystemDialog = () => {
  showSystemNotificationDialog.value = false
  Object.assign(systemNotificationData, {
    title: '',
    content: '',
    level: 1,
    targetType: 0 // Reset to default
  })
}

const closeDetailDialog = () => {
  showDetailDialog.value = false
  selectedNotification.value = null
}

// 获取类型文本
const getTypeText = (type: number) => {
  const typeMap: Record<number, string> = {
    1: '系统',
    2: '订单',
    3: '商品',
    4: '安全'
  }
  return typeMap[type] || '未知'
}

// 获取级别文本
const getLevelText = (level: number) => {
  const levelMap: Record<number, string> = {
    1: '普通',
    2: '重要',
    3: '紧急'
  }
  return levelMap[level] || '未知'
}

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  return new Date(dateStr).toLocaleString('zh-CN')
}

// 格式化时间为LocalDateTime兼容格式 (yyyy-MM-dd HH:mm:ss)
const formatDateTimeForBackend = (date: Date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 页面加载时获取数据
onMounted(() => {
  loadNotificationList()
})
</script>

<style scoped>
.notification-management {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-section {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  gap: 15px;
  align-items: end;
  flex-wrap: wrap;
}

.filter-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.filter-item label {
  font-weight: 500;
  color: #555;
  font-size: 12px;
}

.form-input, .form-select, .form-textarea {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.filter-item .form-input,
.filter-item .form-select {
  width: 120px;
}

.stats-section {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  display: flex;
  align-items: center;
  gap: 15px;
  flex: 1;
  min-width: 180px;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.stat-icon.total {
  background: #17a2b8;
}

.stat-icon.unread {
  background: #ffc107;
}

.stat-icon.urgent {
  background: #dc3545;
}

.stat-icon.system {
  background: #6f42c1;
}

.stat-info h3 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.stat-info p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.table-container {
  background: white;
  border-radius: 8px;
  overflow-x: auto;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  min-width: 1400px;
}

.data-table th {
  background: #f8f9fa;
  padding: 12px 8px;
  text-align: left;
  font-weight: 600;
  border-bottom: 2px solid #dee2e6;
  font-size: 12px;
}

.data-table td {
  padding: 12px 8px;
  border-bottom: 1px solid #dee2e6;
  vertical-align: middle;
  font-size: 12px;
}

.notification-title .title-content {
  display: flex;
  align-items: center;
  gap: 5px;
}

.notification-title .unread {
  color: #007bff;
  font-weight: 600;
}

.has-action {
  color: #28a745;
}

.notification-content .content-preview {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #666;
  line-height: 1.4;
}

.type-badge, .level-badge {
  padding: 3px 8px;
  border-radius: 12px;
  font-size: 10px;
  font-weight: 500;
}

.type-1 {
  background: #e2e3e5;
  color: #383d41;
}

.type-2 {
  background: #d1ecf1;
  color: #0c5460;
}

.type-3 {
  background: #d4edda;
  color: #155724;
}

.type-4 {
  background: #f8d7da;
  color: #721c24;
}

.level-1 {
  background: #d4edda;
  color: #155724;
}

.level-2 {
  background: #fff3cd;
  color: #856404;
}

.level-3 {
  background: #f8d7da;
  color: #721c24;
}

.read-badge {
  display: flex;
  align-items: center;
  gap: 3px;
  padding: 3px 6px;
  border-radius: 8px;
  font-size: 10px;
}

.read-badge.read {
  background: #d4edda;
  color: #155724;
}

.read-badge.unread {
  background: #fff3cd;
  color: #856404;
}

.related-info .related-type {
  color: #007bff;
  font-weight: 500;
}

.related-info .related-id {
  color: #666;
  margin-left: 3px;
}

.no-relation {
  color: #999;
  font-style: italic;
}

.batch-actions {
  background: #e3f2fd;
  padding: 15px 20px;
  border-radius: 8px;
  margin: 20px 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border: 1px solid #bbdefb;
}

.batch-info {
  color: #1976d2;
  font-weight: 500;
}

.batch-buttons {
  display: flex;
  gap: 10px;
}

.actions .btn {
  margin-right: 3px;
  margin-bottom: 3px;
}

.btn {
  padding: 6px 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 11px;
  display: inline-flex;
  align-items: center;
  gap: 3px;
  transition: all 0.2s;
}

.btn-sm {
  padding: 3px 6px;
  font-size: 10px;
}

.btn-primary {
  background: #007bff;
  color: white;
}

.btn-secondary {
  background: #6c757d;
  color: white;
}

.btn-info {
  background: #17a2b8;
  color: white;
}

.btn-warning {
  background: #ffc107;
  color: #212529;
}

.btn-success {
  background: #28a745;
  color: white;
}

.btn-danger {
  background: #dc3545;
  color: white;
}

.btn-outline {
  background: transparent;
  border: 1px solid #ddd;
  color: #333;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.page-numbers {
  display: flex;
  gap: 5px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.notification-form-modal {
  width: 90%;
  max-width: 800px;
}

.system-notification-modal {
  width: 90%;
  max-width: 600px;
}

.notification-detail-modal {
  width: 90%;
  max-width: 700px;
}

.modal-content {
  background: #ffffff;
  border-radius: 4px;
  max-height: 90vh;
  overflow-y: auto;
  border: 1px solid #e8e8e8;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

.modal-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: #333333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  color: #999999;
  padding: 4px;
  line-height: 1;
  transition: color 0.2s;
}

.close-btn:hover {
  color: #666666;
}

.modal-body {
  padding: 20px;
  background: #ffffff;
}

.modal-footer {
  padding: 16px 20px;
  border-top: 1px solid #f0f0f0;
  text-align: right;
  background: #fafafa;
}

.form-row {
  display: flex;
  gap: 20px;
  margin-bottom: 18px;
}

.form-group {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.form-group label {
  font-weight: 400;
  color: #666666;
  font-size: 14px;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 24px;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 500;
  color: #333333;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 8px;
}

.detail-row {
  display: flex;
  margin-bottom: 8px;
  align-items: flex-start;
}

.detail-row .label {
  font-weight: 400;
  color: #666666;
  width: 100px;
  flex-shrink: 0;
  font-size: 14px;
}

.detail-row .value {
  color: #333333;
  font-size: 14px;
}

.extra-data {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 4px;
  font-size: 13px;
  color: #495057;
  border: 1px solid #e9ecef;
  white-space: pre-wrap;
}
</style> 